const Koa = require('koa');
const KoaRouter = require('koa-router');
const KoaBodyParser = require('koa-bodyparser');
const KoaCors = require('koa-cors');
const { runOTA, runArea, runCatering, runRank, runBill, runCateringStore } = require('./service/wx');
const { addOTARecord, addArea, addRank, addBill, addCatering } = require('./service/lark');
const dayjs = require('dayjs');
const areaMapData = require('./utils/area_record');
require('dotenv').config();

const app = new Koa();

const orderType = {
    '0': '客户端订单',
    '1': '吧台订单',
    '2': '网管代下单',
    '4': '交班销售补单',
    '5': '积分兑换',
    '6': '外卖订单',
    '7': '公众号充值网费',
    '8': '小程序订单',
}

app.use(KoaCors({
    origin: '*'
}))

const router = new KoaRouter();

router.get('/', async ctx => {
    ctx.body = '欢迎光临云游电竞！'
})

router.post('/runOTA', async ctx => {
    const params = ctx.request.body;
    const startTime = params.startTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00');
    const endTime = params.endTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59');
    const otaOriginData = await runOTA(params.store, startTime, endTime);
    // 处理数据
    const otaLarkData = [];
    otaOriginData.forEach(d => {
        otaLarkData.push({
            fields: {
                "团购": d.name,
                "平台": d.platform,
                "销量": d.count,
                "金额": d.money,
                "日期": new Date(params.startTime || dayjs().subtract(1, 'day')).getTime()
            }
        })
    })
    await addOTARecord(params.store, otaLarkData);
    ctx.body = {
        code: 0,
        data: otaOriginData
    }
})

router.post('/runArea', async ctx => {
    const params = ctx.request.body;
    const startTime = params.startTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00');
    const endTime = params.endTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59');
    const areaOriginData = await runArea(params.store, startTime, endTime);
    if (params.store === 'fujin' || params.store === 'yingmenkou' || params.store === 'huarun') {
        // 历史遗留原因数据清洗
        const areaData = [];
        const doubleConfortData = {
            fields: {
                '上机时长': 0,
                '上机人次': 0,
                '上机人数': 0,
                '区域总消耗': 0,
                '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
                '区域': [areaMapData[params.store]['豪华舒适双人包房']]
            }
        };
        const doubleFpsData = {
            fields: {
                '上机时长': 0,
                '上机人次': 0,
                '上机人数': 0,
                '区域总消耗': 0,
                '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
                '区域': [areaMapData[params.store]['豪华FPS双人包房']]
            }
        };
        const doubleConfortSecretData = {
            fields: {
                '上机时长': 0,
                '上机人次': 0,
                '上机人数': 0,
                '区域总消耗': 0,
                '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
                '区域': [areaMapData[params.store]['豪华舒适双人胶囊房']]
            }
        }
        const allienwareDoubleData = {
            fields: {
                '上机时长': 0,
                '上机人次': 0,
                '上机人数': 0,
                '区域总消耗': 0,
                '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
                '区域': [areaMapData[params.store]['外星人开黑房']]
            }
        }
        const zoiweDoubleData = {
            fields: {
                '上机时长': 0,
                '上机人次': 0,
                '上机人数': 0,
                '区域总消耗': 0,
                '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
                '区域': [areaMapData[params.store]['卓威开黑房']]
            }
        }
        areaOriginData.forEach(d => {
            if (d.areaName.includes('舒适双包')) {
                doubleConfortData.fields['上机时长'] += Number(d.onTimeHours);
                doubleConfortData.fields['上机人次'] += Number(d.personCount);
                doubleConfortData.fields['上机人数'] += Number(d.personNum);
                doubleConfortData.fields['区域总消耗'] += Number(d.totalCost);
            } else if(d.areaName.includes('FPS双包')) {
                doubleFpsData.fields['上机时长'] += Number(d.onTimeHours);
                doubleFpsData.fields['上机人次'] += Number(d.personCount);
                doubleFpsData.fields['上机人数'] += Number(d.personNum);
                doubleFpsData.fields['区域总消耗'] += Number(d.totalCost);
            } else if (d.areaName.includes('舒适双人胶囊房')) {
                doubleConfortSecretData.fields['上机时长'] += Number(d.onTimeHours);
                doubleConfortSecretData.fields['上机人次'] += Number(d.personCount);
                doubleConfortSecretData.fields['上机人数'] += Number(d.personNum);
                doubleConfortSecretData.fields['区域总消耗'] += Number(d.totalCost);
            } else if (d.areaName.includes('外星人开黑房')) {
                allienwareDoubleData.fields['上机时长'] += Number(d.onTimeHours);
                allienwareDoubleData.fields['上机人次'] += Number(d.personCount);
                allienwareDoubleData.fields['上机人数'] += Number(d.personNum);
                allienwareDoubleData.fields['区域总消耗'] += Number(d.totalCost);
            } else if(d.areaName.includes('卓威开黑房')) {
                zoiweDoubleData.fields['上机时长'] += Number(d.onTimeHours);
                zoiweDoubleData.fields['上机人次'] += Number(d.personCount);
                zoiweDoubleData.fields['上机人数'] += Number(d.personNum);
                zoiweDoubleData.fields['区域总消耗'] += Number(d.totalCost);
            } else {
                areaData.push({
                    fields: {
                        '上机时长': Number(d.onTimeHours),
                        '上机人次': Number(d.personCount),
                        '上机人数': Number(d.personNum),
                        '区域总消耗': Number(d.totalCost),
                        '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
                        '区域': [areaMapData[params.store][d.areaName]]
                    }
                })
            }
        })
        if (params.store === 'yingmenkou' || params.store === 'fujin') {
            areaData.push(doubleConfortData);
            areaData.push(doubleFpsData)
        }
        params.store === 'huarun' && areaData.push(allienwareDoubleData);
        params.store === 'huarun' && areaData.push(zoiweDoubleData);
        await addArea(params.store, areaData);
    }
    if (params.store === 'hongguangli') {
        const areaData = handleHGLArea(params, areaOriginData);
        await addArea(params.store, areaData);
    }
    ctx.body = {
        code: 0,
        data: areaOriginData
    }
})
router.post('/runCatering', async ctx => {
    const params = ctx.request.body;
    const startTime = params.startTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00');
    const endTime = params.endTime || dayjs().format('YYYY-MM-DD 00:00:00');
    // await runCateringStore(params.store);
    const cateringOriginData = await runCatering(params.store, startTime, endTime);
    const cateringData = [];
    let flag = true;
    cateringOriginData.forEach(d => {
        cateringData.push({
            fields: {
                "名称": d.product_name,
                "展示分类": d.show_product_type_name,
                "商品类型": d.product_type_name,
                "销量": Number(d.buy_count),
                "价格": Number(d.total_price),
                "订单来源": orderType[d.order_type],
                "支付时间": new Date(d.pay_time_all).getTime(),
                "完成时间": new Date(d.finish_time).getTime(),
                "筛选标记": flag ? '是' : '否'
            }
        })
        flag = false;
    })
    await addCatering(params.store, cateringData);
    ctx.body = {
        code: 0,
        data: cateringOriginData
    };
})

router.post('/runRank', async ctx => {
    const params = ctx.request.body;
    const startTime = params.startTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00');
    const endTime = params.endTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59');
    const rankOriginData = await runRank(params.store, startTime, endTime);
    const rankData = [];
    rankOriginData.forEach(d => {
        rankData.push({
            fields: {
                '充值': d.rechargeQuota,
                '数量': d.totalNum,
                '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime()
            }
        })
    })
    await addRank(params.store, rankData);
    ctx.body = {
        code: 0,
        data: rankOriginData
    }
})

router.post('/runBill', async ctx => {
    const params = ctx.request.body;
    const startTime = params.startTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00');
    const endTime = params.endTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59');
    const billOriginData = await runBill(params.store, startTime, endTime);
    const otaOriginData = await runOTA(params.store, startTime, endTime);
    const billData = {fields: {}};
    billOriginData.forEach(d => {
        billData.fields['网费'] = d.fee_income;
        billData.fields['餐饮'] = d.goods_income;
        billData.fields['租赁'] = d.lease_deposit_charge_all;

    })
    const douyinOta = otaOriginData.filter(d => d.platform === '抖音').reduce((prev, cur) => {
        return prev + cur.money;
    }, 0)
    const meituanOta = otaOriginData.filter(d => d.platform === '美团').reduce((prev, cur) => {
        return prev + cur.money;
    }, 0)
    billData.fields['抖音'] = douyinOta;
    billData.fields['美团'] = meituanOta;
    billData.fields['日期'] = new Date(startTime).getTime();
    await addBill(params.store, [billData])
    ctx.body = {
        code: 0,
        data: billData
    }
})
app.use(KoaBodyParser());

app.use(router.routes()).use(router.allowedMethods());

app.listen(process.env.PORT, () => {
    console.log('Server is listening at http://127.0.0.1' + ':' + process.env.PORT);
})


const handleHGLArea = (params, areaOriginData) => {
    const areaData = [];
    const doubleConfortData = {
        fields: {
            '上机时长': 0,
            '上机人次': 0,
            '上机人数': 0,
            '区域总消耗': 0,
            '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
            '区域': [areaMapData[params.store]['2K400hz双人包']]
        }
    }; 
    const doubleFpsData = {
        fields: {
            '上机时长': 0,
            '上机人次': 0,
            '上机人数': 0,
            '区域总消耗': 0,
            '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
            '区域': [areaMapData[params.store]['卓威280hz双人包']]
        }
    };
    areaOriginData.forEach(d => {
        if (d.areaName.includes('2K400hz双人包')) {
            doubleConfortData.fields['上机时长'] += Number(d.onTimeHours);
            doubleConfortData.fields['上机人次'] += Number(d.personCount);
            doubleConfortData.fields['上机人数'] += Number(d.personNum);
            doubleConfortData.fields['区域总消耗'] += Number(d.totalCost);
        } else if(d.areaName.includes('卓威280hz双人包')) {
            doubleFpsData.fields['上机时长'] += Number(d.onTimeHours);
            doubleFpsData.fields['上机人次'] += Number(d.personCount);
            doubleFpsData.fields['上机人数'] += Number(d.personNum);
            doubleFpsData.fields['区域总消耗'] += Number(d.totalCost);
        } else {
            areaData.push({
                fields: {
                    '上机时长': Number(d.onTimeHours),
                    '上机人次': Number(d.personCount),
                    '上机人数': Number(d.personNum),
                    '区域总消耗': Number(d.totalCost),
                    '日期': new Date(params.startTime || dayjs().subtract(1, 'day')).getTime(),
                    '区域': [areaMapData[params.store][d.areaName]]
                }
            })
        }
    })
    return [...areaData, doubleConfortData, doubleFpsData];
}